package github.sf.fw.tools.config;


import github.sf.fw.PackageInfo;
import org.apache.commons.lang3.StringUtils;

import java.util.Properties;

public class AppConfig {
    public static final String SCAN_PACKAGE = "app.config.scan.package";
    private final static String configPrefix = "app.config";
    private final static Properties confProps = new Properties();

    static {
        confProps.put(SCAN_PACKAGE, new AppConfig(null, PackageInfo.class.getPackage().getName()));
        Properties properties = System.getProperties();
        properties.entrySet().stream()
                .filter(entry -> {
                    Object key = entry.getKey();
                    if (String.class.isAssignableFrom(key.getClass())) {
                        return ((String) key).startsWith(configPrefix);
                    }
                    return false;
                })
                .forEach(entry -> {
                    Object entryValue = entry.getValue();
                    if (String.class.isAssignableFrom(entryValue.getClass())) {
                        AppConfig appConfig = new AppConfig((String) entry.getValue(), null);
                        confProps.put(entry.getKey(), appConfig);
                    }
                });
    }

    private final String value;
    private final String defalutValue;

    public AppConfig(String value, String defalutValue) {
        this.value = value;
        this.defalutValue = defalutValue;
    }

    public static String getConfig(String key) {
        Object confObj = confProps.get(key);
        if (!AppConfig.class.isAssignableFrom(confObj.getClass())) {
            throw new IllegalStateException(String.format("key %s对应的类型为%s,不为%s", key, AppConfig.class.getName(), confObj.getClass().getName()));
        }
        AppConfig appConfObj = (AppConfig) confObj;
        if (StringUtils.isEmpty(appConfObj.value)) {
            return appConfObj.defalutValue;
        }
        return appConfObj.value;
    }
}
